package com.zxd.interview.eightthread.uncaughtexception;

import lombok.extern.slf4j.Slf4j;

/**
 * 自己实现 UncaughtExceptionHandler 接口，实现主线程捕获子线程的异常
 */
@Slf4j
public class MyCaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    private final String name;

    public MyCaughtExceptionHandler(String name) {
        this.name = name;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        log.info(name);
        log.info("{} uncaughtException => {}", t.getName(), e.getMessage());
        log.info("手动中止线程");
    }/**
     通过设置自定义的捕获器，实现了统一的异常处理，这种处理方式显然更为优雅
        注意Thread.setDefaultUncaughtExceptionHandler(new MyCaughtExceptionHandler("主线程自定义捕获器")); 方式则主线程也被囊括在内一起被处理
     主线程异常/ by zero

     21:32:16.996 [线程4] INFO  c.z.i.u.MyCaughtExceptionHandler - 主线程自定义捕获器
     21:32:16.996 [线程3] INFO  c.z.i.u.MyCaughtExceptionHandler - 主线程自定义捕获器
     21:32:16.996 [线程2] INFO  c.z.i.u.MyCaughtExceptionHandler - 主线程自定义捕获器
     21:32:16.996 [线程1] INFO  c.z.i.u.MyCaughtExceptionHandler - 主线程自定义捕获器
     21:28:45.394 [线程1] INFO  c.z.i.u.MyCaughtExceptionHandler - 线程1 uncaughtException => 线程1 抛出异常
     21:28:45.394 [线程2] INFO  c.z.i.u.MyCaughtExceptionHandler - 线程2 uncaughtException => 线程2 抛出异常
     21:28:45.394 [线程4] INFO  c.z.i.u.MyCaughtExceptionHandler - 线程4 uncaughtException => 线程4 抛出异常
     21:28:45.394 [线程3] INFO  c.z.i.u.MyCaughtExceptionHandler - 线程3 uncaughtException => 线程3 抛出异常
     21:28:45.399 [线程1] INFO  c.z.i.u.MyCaughtExceptionHandler - 手动中止线程
     21:28:45.399 [线程2] INFO  c.z.i.u.MyCaughtExceptionHandler - 手动中止线程
     21:28:45.399 [线程4] INFO  c.z.i.u.MyCaughtExceptionHandler - 手动中止线程
     21:28:45.400 [线程3] INFO  c.z.i.u.MyCaughtExceptionHandler - 手动中止线程

     */
}
